package algorithm.leetcode

object SisterStr {

    fun buddyStrings2(A : String, B : String) : Boolean{
            //ab ba   aa, aa  ab, ab
        if(A.length != B.length || A.length == 1) return false
        val len = A.length
        val idx = IntArray(2)
        var ct = -1
        if(A == B){
            val cdx = IntArray(26)
            for (c in A){
                val which = c - 'a'
                cdx[which] += 1
                if (cdx[which] > 1)
                    return true
            }
            return false
        }else{
            for (i in 0 until len) {
                val a = A[i]
                val b = B[i]
                if (a != b) {
                    ct++
                    if (ct > 1) {
                        return false
                    } else {
                        idx[ct] = i
                    }
                }
            }
            if(ct == 1){
                return A[idx[0]] == B[idx[1]] && A[idx[1]] == B[idx[0]]
            }
            return false
        }
    }

    fun buddyStrings(A: String, B: String): Boolean {
        //ab ba   aa, aa  ab, ab
        if(A.length != B.length) return false
        val len = A.length
        val idx = IntArray(2)
        var ct = -1
        var isSameCount = 0
        val map = mutableMapOf<Char, Int>()
        for (i in 0 until len){
            val a = A[i]
            val b = B[i]
            if(a != b){
                ct++
                if(ct > 1){
                    return false
                }else{
                    idx[ct] = i
                }
            }else{
                isSameCount++
                val c = map[a]
                if(c == null){
                    map[a] = 1
                }else{
                    map[a] = c+1
                }
            }
        }
        if(isSameCount == len){
            if(map.size == 1) return true
            val cc = map.values
            for (c in cc){
                if(c > 1) return true
            }
        }

        if(ct == 1){
            return A[idx[0]] == B[idx[1]] && A[idx[1]] == B[idx[0]]
        }
        return false
    }

    @JvmStatic
    fun main(args: Array<String>) {
        println(SisterStr.buddyStrings2("aaaaaaabc", "aaaaaaacb"))
    }
}